package com.shigu.admin.action;

import com.shigu.component.enums.SessionEnum;
import com.shigu.component.shiro.AuthorityUser;
import com.shigu.weixin.exceptions.UtilsException;
import com.shigu.weixin.service.WxUserService;
import com.shigu.weixin.vo.WebToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/*
 * create by  过儿  2019-05-15
 *
 */
@Controller
public class WxLoginController {
    @Autowired
    WxUserService wxUserService;

    @RequestMapping("wxlogin")
    public String wxlogin(String code, String state, HttpSession session) throws UnsupportedEncodingException, UtilsException {

        WebToken token = wxUserService.mkWebToken(code);

        if (token == null) {
            throw new UtilsException("微信授权登陆失败，请联系管理员");
        }

        if (state.contains("!")) {
            state = state.replace("!", "%");
        }
        //获取unionid
//        String unionid = null;
//        try {
//            unionid = wxUserService.getGzhUnionId(token.getOpenid());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        Long mallUserId = wxUserService.addOpeniidToUser(token.getOpenid());
        // 用户存入session
        AuthorityUser user = new AuthorityUser();
        user.setUserId(mallUserId);

        session.setAttribute(SessionEnum.GZH_OPENIID.toString(), token.getOpenid());
        session.setAttribute(SessionEnum.LOGIN_USER.toString(), user);
        String backUrl = URLDecoder.decode(state, "utf-8");

        if (backUrl.startsWith("http:")) {
            backUrl = backUrl.replace("http:", "https:");
        }

        return "redirect:" + backUrl;
    }

}
